<template>
  <!-- 首页根组件 -->
  <div class="wapper">
    <tou-bu></tou-bu>
    <lun-bo-tu :list="swiperList"></lun-bo-tu>
    <icon-lie-biao :list="iconList"></icon-lie-biao>
    <yan-xuan :list="strictList"></yan-xuan>
    <pai-hang-bang></pai-hang-bang>
    <tou-tiao></tou-tiao>
    <bai-ke></bai-ke>
    <lou-xun-gong-lue></lou-xun-gong-lue>
    <xin-fang-tui-jian :list="BridalchamberList"></xin-fang-tui-jian>
    <di-bu-xin-xi></di-bu-xin-xi>
    <go-top></go-top>
  </div>
</template>

<script>
  // 1.引入组件
  import TouBu from './components/TouBu'
  import LunBoTu from './components/LunBoTu'
  import IconLieBiao from './components/IconLieBiao'
  import YanXuan from './components/YanXuan'
  import PaiHangBang from './components/PaiHangBang'
  import TouTiao from './components/TouTiao'
  import BaiKe from './components/BaiKe'
  import LouXunGongLue from './components/LouXunGongLue'
  import XinFangTuiJian from './components/XinFangTuiJian'
  import DiBuXinXi from './components/DiBuXinXi'
  import goTop from '../../common/gotop/goTop'

  // axios 数据请求
  import axios from 'axios'
  import {mapState} from 'vuex'

  export default {
    name: 'Home',
    data () {
      return {
        // ajax 数据保存
        lastCity: '',
        swiperList: [],
        iconList: [],
        strictList: [],
        BridalchamberList: []
      }
    },
    // 2.注册组件
    components: {
      TouBu,
      LunBoTu,
      IconLieBiao,
      YanXuan,
      PaiHangBang,
      TouTiao,
      BaiKe,
      LouXunGongLue,
      XinFangTuiJian,
      DiBuXinXi,
      goTop
    },
    // 计算属性
    computed: {
      ...mapState(['city'])
    },
    // 方法
    methods: {
      getHomeInfo () {
        // 请求 Ajax 数据
        axios.get('/api/index.json?city=' + this.city)
          // .then()前的方法执行完后再执行then()内部的程序，这样就避免了，数据没获取到等的问题。
          .then(this.getHomeInfoSuss)
      },
      getHomeInfoSuss (res) {
        // 获取数据成功，则打印出来
        console.log(res)
        // 拿到数据后，把JSON 数据中的data 值赋值给res 变量
        res = res.data
        // res 正确返回，并且res中有rest/data项
        if (res.ret && res.data) {
          // res.data 赋值 给 data 变量，（减少字符长度）
          const data = res.data
          this.swiperList = data.swiperList
          this.iconList = data.iconList
          this.strictList = data.strictList
          this.BridalchamberList = data.BridalchamberList
        }
      }
    },
    // 生命周期钩子- 当页面挂载完成， 自动执行 getHomeInfo方法
    mounted () {
      this.getHomeInfo()
      console.log('mounted')
      //  保存当前数据
      this.lastCity = this.city
      window.addEventListener('scroll', this.handleScroll)
    },
    // 当根组件使用，keep-alive 缓存数据时，会多出一个activated 钩子
    activated () {
      // 实现切换城市，重新发送 ajax请求，如果相同，则不重新发送，如果切换了城市 就重新发送Ajax 请求
      if (this.lastCity !== this.city) {
        this.lastCity = this.city
        this.getHomeInfo()
      }
      console.log('activated')
    }
  }
</script>

<style scoped>

</style>
